import { BasePromiseResultType } from '#/request';
import { RequestStatus } from '@/enums/request';
import useToastMsg from '@/hooks/sysMsg';
import { getPlatformInfo } from '@/utils/platform';
const toastMsg= useToastMsg()
const useResponseInterceptor = {
  successHooks: (res: any): Promise<any> => {
    if (res.data.code !== RequestStatus.SUCCESS) {
      return Promise.resolve(false)
    }
    return Promise.resolve(true)
  },
  errorHooks: (res: any): Promise<any> => {
    return Promise.reject(false)
  }
};

const useRequestInterceptor = (method: string, url: string, params: any, data: any, header?: any, responesData?: any): any => {
  // toastMsg.successMsg(getPlatformInfo().baseUrl + url)
  const requestData: any = {
    url: getPlatformInfo().baseUrl + url,
    method,
    data: params || data,
    timeout: 6000,
    header: {
      'X-Requested-With': 'XMLHttpRequest',
      'Content-Type': 'application/json',
      'content-encoding': 'gzip',
      ...header
    }
  };

  if (responesData) {
    Object.keys(responesData).forEach(item => (requestData[item] = responesData[item]));
  }
  //   if(){
  requestData.header.Authorization = 'I am token';
  //   }
  return requestData;
};

export const getRequest = <T>(method: string, url: string, params: any, data: any, header?: any, responesData?: any,): Promise<BasePromiseResultType<T>> => {
  return new Promise(resolve => {
    uni.request({
      ...useRequestInterceptor(method, url, params, data, header, responesData),
      success: async (res: any) => {
        const result = await useResponseInterceptor.successHooks(res);
        if(result){
          resolve([res.data, null])
        }else{
          resolve([null, res.data]);
        }
      }, fail:async (err: any) => {
        const result = useResponseInterceptor.errorHooks(err);
        resolve([null, err.message]);
      }
    })
  });
};
